<?php

namespace app\admin\controller\detection;

use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 检测订单
 *
 * @icon fa fa-circle-o
 */
class Orders extends Backend
{

    /**
     * Orders模型对象
     * @var \app\admin\model\detection\Orders
     */
    protected $model = null;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = true;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'end_adminid';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\detection\Orders;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("genderdataList", $this->model->getGenderdataList());
        $this->view->assign("isDivingList", $this->model->getIsDivingList());
        $this->view->assign("lookCheckList", $this->model->getLookCheckList());
        $this->view->assign("lowCheckList", $this->model->getLowCheckList());
        $this->view->assign("obdCheckList", $this->model->getObdCheckList());
        $this->view->assign("huanCheckList", $this->model->getHuanCheckList());
        $this->view->assign("anCheckList", $this->model->getAnCheckList());
        $this->view->assign("sanCheckList", $this->model->getSanCheckList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['admin','user','detection'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->star_nums = $row->star_nums ? $row->star_nums.'星' : '暂无评价';
                $row->getRelation('admin')->visible(['nickname']);
				$row->getRelation('user')->visible(['nickname']);
				$row->getRelation('detection')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row->status < 2)
                $this->error('请先开始检测');
            if($row->status > 2)
                $this->error('检测已结束');
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        //如果填写了验车结束时间，自动结束验车
        if($params['overtime'])
        {
            if(strtotime($params['overtime']) <= $row->begintime)
                $this->error('结束时间不合法');
            if($row->type == 1 && ($params['look_check'] == 0 || $params['low_check'] == 0 || $params['obd_check'] == 0 || $params['huan_check'] == 0 || $params['an_check'] == 0 || $params['san_check'] == 0))
                $this->error('存在检测中的检测项');
            if($row->type == 2 && $params['san_check'] == 0)
                $this->error('请先完成三电检测');
            $params['status'] = 3;
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if($row->status == 3)
            {
                //给检测厂返利
                User::money($row->end_price,db('admin')->where(['id'=>$row->end_adminid])->value('userid'),'检测订单'.$row->numbers.'收益到账');
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 开始检测
     */
    public function begin()
    {
        $ids = $this->request->param('ids');
        $data = $this->model->find($ids);
        if($data->status == 0)
            $this->error('订单未支付');
        if($data->end_adminid != $this->auth->id)
            $this->error('暂无权限');
        if($data->status > 1)
            $this->error('检测已开始');
        $data->status = 2;
        $data->begintime = time();
        $data->save();
        $this->success('操作成功');
    }
}
